'use strict';

$(function () {
    layui.use(['form', 'layer', 'element'], function () {
        var form = layui.form(),
            layer = layui.layer,
            element = layui.element();

        var curIndex = 0,
            attachments = [],
            formData = {};

        getReviewers();

        // 监听模板类型的变化
        form.on('select(type)', function (data) {
            if (data.value === 'summary') {
                $('.resource-template-box').hide();
                $('.common-template-box').show();
            } else {
                $('.resource-template-box').show();
                $('.common-template-box').hide();
            }
        });

        // 监听工作类型改变
        form.on('select(workType)', function (data) {
            if (data.value == 1) {
                $(data.elem).parents('.col-md-7').next().next().show();
            } else {
                $(data.elem).parents('.col-md-7').next().next().hide();
            }
        });

        // 生成工作类型和项目的options
        function generateOptions() {
            var resourcesOptions = '',
                projectsOptions = '';

            for (var key in resources) {
                resourcesOptions += '<option value="' + resources[key].id + '">' + resources[key].name + '</option>';
            }
            resourcesOptions += '<option value="0">休假</option>';

            for (var key in projects) {
                projectsOptions += '<option value="' + projects[key].id + '">' + projects[key].label + '</option>';
            }
            projectsOptions += '<option value="0">其它项目</option>';

            return {
                resourcesOptions: resourcesOptions,
                projectsOptions: projectsOptions
            };
        }

        // 添加工作内容项
        $('.add-summary-item-btn').click(function () {
            curIndex++;
            // var itemLength = $('.resource-template-box .layui-tab .layui-tab-title').children().length;
            var options = generateOptions();

            // 准备插入本周总结的dom结构
            var dom = ['<div class="layui-tab-item layui-show">', '<div class="row" style="margin-top: 20px;">', '<div class="col-md-7">', '<div class="layui-form-item">', '<label class="layui-form-label">工作类型</label>', '<div class="layui-input-block">', '<select name="resources[' + curIndex + '][resource_id]" lay-filter="workType">', options.resourcesOptions, '</select>', '</div>', '</div>', '</div>', '<div class="col-md-5">', '<div class="layui-form-item">', '<label class="layui-form-label">工作耗时</label>', '<div class="layui-input-block">', '<input type="text" name="resources[' + curIndex + '][scale]" class="layui-input" placeholder="工作耗时(天数)">', '</div>', '</div>', '</div>', '<div class="col-md-12">', '<div class="layui-form-item">', '<label class="layui-form-label">项目名称</label>', '<div class="layui-input-block">', '<select name="resources[' + curIndex + '][project_id]">', options.projectsOptions, '</select>', '</div>', '</div>', '</div>', '<div class="col-md-12">', '<div class="layui-form-item">', '<label class="layui-form-label">工作内容</label>', '<div class="layui-input-block">', '<textarea name="resources[' + curIndex + '][info]" rows="15" class="layui-textarea" placeholder="详细工作内容"></textarea>', '</div>', '</div>', '</div>', '</div>', '</div>'].join('');

            element.tabAdd('summary', {
                title: '总结内容(' + (curIndex + 1) + ')',
                content: dom //支持传入html,
            });

            var titles = $('.resource-template-box .layui-tab .layui-tab-title').children();
            var contents = $('.resource-template-box .layui-tab .layui-tab-content').children();

            titles.each(function (index) {
                $(this).removeClass('layui-this');
                if (index == titles.length - 1) {
                    $(this).addClass('layui-this');
                }
            });

            contents.each(function (index) {
                $(this).removeClass('layui-show');
                if (index == titles.length - 1) {
                    $(this).addClass('layui-show');
                }
            });

            form.render();
            $('html').animate({ scrollTop: 0 }, 'fast');
        });

        // 监听选项卡的删除
        $(document).on('click', '.layui-tab-close', function (e) {
            curIndex--;
            var children = $('.resource-template-box .layui-tab .layui-tab-title').children();
            children.each(function (index) {
                $(this).text('总结内容(' + (index + 1) + ')');
            });
        });

        // 定义 webuploader 配置
        var WebUploaderOptions = {
            auto: false,
            server: '/Summary/upload',
            pick: {
                id: '#FilePick',
                multiple: true
            },
            fileVal: 'Filedata',
            accept: {
                title: 'file',
                extensions: 'zip,rar,jpg,png,jpeg,doc,docx,xls,xlsx,pdf,ppt,pptx'
            },
            method: 'POST'
        };

        // 实例化uploader
        var FileUploader = WebUploader.create(WebUploaderOptions);

        // 上传错误时
        FileUploader.on('error', function (code) {
            var msg = '';
            switch (code) {
                case 'Q_EXCEED_NUM_LIMIT':
                    msg = '只能上传一个文件';
                    break;
                case 'Q_EXCEED_SIZE_LIMIT':
                    msg = '文件大小超出限制';
                    break;
                case 'Q_TYPE_DENIED':
                    msg = '文件格式不允许';
                    break;
                case 'F_DUPLICATE':
                    msg = '文件已存在';
                    break;
                default:
                    msg = code;
            }
            layer.msg(msg, { icon: 2, time: 2000 });
        });

        // 添加到队列时
        FileUploader.on('fileQueued', function (file) {
            var fileItem = '<div class="file-item" id="' + file.id + '">' + '<div class="pull-left"><i class="file-icon file-icon-ext-' + file.ext + '"></i> ' + file.name + '</div>' + '<div class="pull-right"><i class="icon-remove" title="移除该文件"></i></div>' + '<div class="clearfix"></div>' + '</div>';
            $(WebUploaderOptions.pick.id).next().append(fileItem);
        });

        FileUploader.on('uploadBeforeSend', function (block, data, headers) {
            layer.load(2, {
                shade: [0.5, '#fff']
            });
        });

        // 上传成功时
        FileUploader.on('uploadSuccess', function (file, response) {
            if (response) {
                attachments.push({
                    path: response.data.path,
                    name: response.data.name,
                    ext: response.data.ext
                });
            }
        });

        // 当所有文件上传结束时
        FileUploader.on('uploadFinished', function () {
            // 将附件数据插入到表单数据
            formData.attachments = attachments;
            submitSummary();
        });

        // 删除队列文件
        $(document).on('click', '.uploader-attachment-queue .icon-remove', function () {
            var id = $(this).parent().parent().attr('id');
            // 删除队列中的文件
            FileUploader.removeFile(id, true);
            // 删除dom节点
            $(this).parent().parent().remove();
        });

        function submitSummary() {
            formData.content = editor.txt.html();
            // console.log(formData);
            for (var key in formData) {
                if (formData.type == 'resource') {
                    if (/^resources\[\d+\]\[scale\]$/.test(key)) {
                        if (!formData[key]) {
                            layer.closeAll();
                            layer.msg('工作耗时不能为空', {
                                icon: 2,
                                time: 2000
                            });
                            return false;
                        }
                    }
                    if (/^resources\[\d+\]\[info\]$/.test(key)) {
                        if (!formData[key]) {
                            layer.closeAll();
                            layer.msg('工作内容不能为空', {
                                icon: 2,
                                time: 2000
                            });
                            return false;
                        }
                    }
                }
            }
            $.post('/summary/store', formData, function (response) {
                if (response.code) {
                    layer.closeAll();
                    layer.msg(response.msg, {
                        icon: 2,
                        time: 2000
                    });
                } else {
                    location.href = '/summary/detail?id=' + response.data.id;
                }
            }, 'json');
        }

        // 获取指定时间年份和周数
        var myDate = new Date();
        $('.title').val(myDate.getFullYear() + '年第' + getWeekOfYear() + '周工作总结');

        // 保存
        form.on('submit(save)', function (data) {
            formData = data.field;
            if (FileUploader.getFiles().length) {
                FileUploader.upload();
            } else {
                layer.load(2, {
                    shade: [0.5, '#fff']
                });
                submitSummary();
            }
        });
    });
});

function getWeekOfYear() {
    var today = new Date();
    var firstDay = new Date(today.getFullYear(), 0, 1);
    var dayOfWeek = firstDay.getDay();
    var spendDay = 1;
    if (dayOfWeek != 0) {
        spendDay = 7 - dayOfWeek + 1;
    }
    firstDay = new Date(today.getFullYear(), 0, 1 + spendDay);
    var d = Math.ceil((today.valueOf() - firstDay.valueOf()) / 86400000);
    var result = Math.ceil(d / 7);
    return result + 1;
}

/**
 * 渲染loading组件
 * @param container
 * @param text
 */
function renderLoading(container) {
    var text = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '加载中...';

    $(container).html(['<i class="layui-icon icon-spin text-muted" style="font-size: 30px;">&#xe63d;</i>' + ' ' + text].join(''));
}

/**
 * 获取评审人和抄送人数据
 * @param params 当前审批类别额外提供的参数
 */
function getReviewers() {
    // loading
    renderLoading('#reviewers-block', '');
    renderLoading('#cc-block', '');

    $.post('/summary/getReviewers', function (response) {
        if (response.code) {
            alert(response.message);
        } else {
            reviewResult = response.data;
            renderUserList('reviewers', false, response.data.reviewers, '#reviewers-block', false);
            renderUserList('cc', false, response.data.cc, '#cc-block');
        }
    }, 'json');
}
